﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Framework;
using Web.CrmContacto.Code;
using CrmContacto.Contracts;
using Web.Framework.Translate;
using CrmContacto.WebApp.Code.InnerClasses;
using CrmContacto.Contracts.Contracts.Search;
using Web.Framework.Misc;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class CategoriaList : BasePage
    {
        private CustomerSearchParam CustomerSearchParamSession
        {
            get
            {
                return (CustomerSearchParam)StoreHelper.GetObject(MiscClass.CustomerSearchParamCacheKey);
            }
            set
            {
                StoreHelper.StoreObject(MiscClass.CustomerSearchParamCacheKey, value);
            }
        }

        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);
            if (!base.NavigationContext.AgregandoContactosACategorias)
            {
                this.GridCategorias.Columns[0].Visible = false;
            }
            else
            {
                this.GridCategorias.Columns[2].Visible = false;
                this.GridCategorias.Columns[3].Visible = false;

                TitleNavContext.Visible = true;

                if (base.NavigationContext.AgregandoContactosACategorias)
                    lblContexto.Text = LocalizationProvider.Instance["Bo.Categorias.Context.AgregandoContactosACategoria"];                
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        LinkButton nuevaCategoriaButton = new LinkButton();
        LinkButton seleccionarCategoriasButton = new LinkButton();
        LinkButton volverButton = new LinkButton();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            
            nuevaCategoriaButton.ID = "BoCategoriasActionMenuNuevaCategoria";
            nuevaCategoriaButton.Text = LocalizationProvider.Instance["Bo.Categorias.ActionMenu.NuevaCategoria"];
            nuevaCategoriaButton.Click += new EventHandler(nuevaCategoriaButton_Click);
            actionButtons.Add(nuevaCategoriaButton);
            
            seleccionarCategoriasButton.ID = "BoCategoriasActionMenuAgregarContactos";
            seleccionarCategoriasButton.Click += new EventHandler(seleccionarCategoriasButton_Click);
            lnkAsociar.Click += new EventHandler(seleccionarCategoriasButton_Click);
            actionButtons.Add(seleccionarCategoriasButton);

            if (base.NavigationContext != null && base.NavigationContext.AgregandoContactosACategorias)
            {
                seleccionarCategoriasButton.Text = LocalizationProvider.Instance["Bo.Categorias.ActionMenu.AgregarCategoriasAContactos"];
                lnkAsociar.Text = seleccionarCategoriasButton.Text;
                nuevaCategoriaButton.Visible = false;
            }
            else
            {
                nuevaCategoriaButton.Visible = true;
                seleccionarCategoriasButton.Visible = false;
            }

            SetJavascriptForClientClickDirtyChech(volverButton);
            volverButton.CausesValidation = false;
            volverButton.ID = "BoCommandVolver";
            volverButton.Text = LocalizationProvider.Instance["Bo.Command.Volver"];
            volverButton.Click += new EventHandler(lnkVolver_Click);
            volverButton.Visible = base.NavigationContext != null && base.NavigationContext.AgregandoContactosACategorias && !String.IsNullOrEmpty(base.NavigationContext.UrlToGoBack);
                        
            base.LoadContextActions(actionButtons);
        }

        protected void lnkVolver_Click(object sender, EventArgs e)
        {
            try
            {
                if (base.NavigationContext != null && base.NavigationContext.AgregandoContactosACategorias)
                {                    
                    string urlToGoBack = base.NavigationContext.UrlToGoBack;
                    SetThisPageToGoBack();
                    //Volver();
                    if (CustomerSearchParamSession != null)
                    {                        
                        base.NavigationContext.AgregandoContactosACategorias = false;
                        Response.Redirect(urlToGoBack + "?search=1&addingCategoriasOk=0", true);
                    }                  
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void seleccionarCategoriasButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (base.NavigationContext.AgregandoContactosACategorias)
                {
                    List<int> categoriasIds = GetCheckedItemsId();

                    if (CustomerSearchParamSession != null)
                    {
                        WebServiceHelper.AddCategoriasAContactos(CustomerSearchParamSession, categoriasIds);

                        string urlToGoBack = base.NavigationContext.UrlToGoBack;
                        SetThisPageToGoBack();
                        //Volver();                       
                        Response.Redirect(urlToGoBack + "?search=1&addingCategoriasOk=1", true);                                    
                    }
                }               
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void SetThisPageToGoBack()
        {
            this.NavigationContext.UrlToGoBack = Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCategoriaList;
        }

        private void nuevaCategoriaButton_Click(object sender, EventArgs e)
        {
            AgregarNuevaCategoria();
        }

        private List<int> GetCheckedItemsId()
        {
            List<int> selectedRowsIds = new List<int>();
            if (!String.IsNullOrEmpty(this.hidCheckedRows.Value))
            {
                string[] ids = this.hidCheckedRows.Value.Split('#');
                this.hidCheckedRows.Value = string.Empty;
                foreach (string id in ids)
                {
                    if (!String.IsNullOrEmpty(id))
                    {
                        int idInt = Convert.ToInt32(id);
                        if (!selectedRowsIds.Contains(idInt))
                        {
                            selectedRowsIds.Add(idInt);
                        }
                    }
                }
            }

            return selectedRowsIds;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                HasPermissionToSeeMe(CrmSecurity.CATEGORY_MANAGE, CrmSecurity.CUSTOMER_ADDTO_CATEGORY, CrmSecurity.CATEGORY_SEARCH);

                this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.ClientID);

                // HasPermissionToSeeMe(PlanProdSecurity.DESTINO_VER);
                if (!this.IsPostBack)
                {
                    Buscar();
                }                
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected override void ApplySecurity()
        {

            if (base.NavigationContext != null && base.NavigationContext.AgregandoContactosACategorias)
            {
                nuevaCategoriaButton.Visible = false;
                lnkAsociar.Visible =
                seleccionarCategoriasButton.Visible = HasPermissionFor(CrmSecurity.CUSTOMER_ADDTO_CATEGORY);
            }
            else
            {
                lnkAsociar.Visible = false;
                nuevaCategoriaButton.Visible = HasPermissionFor(CrmSecurity.CATEGORY_MANAGE);
                if (this.GridCategorias.DataSource != null)
                {
                    this.GridCategorias.Columns[2].Visible = HasPermissionFor(CrmSecurity.CATEGORY_SEARCH) || HasPermissionFor(CrmSecurity.CATEGORY_MANAGE);
                    this.GridCategorias.Columns[3].Visible = HasPermissionFor(CrmSecurity.CATEGORY_MANAGE);
                }
            }                                                      
        }

        private void Buscar()
        {
            string nombreLike = this.txtNombre.Text;

            List<MaestroBase> categoriaList = WebServiceHelper.GetCategoriasDeContacto(new MaestroBaseSearch() { EmpresaId = BaseWebPage.CompanyId, NombreLike = nombreLike });

            this.GridCategorias.DataSource = categoriaList;
            this.GridCategorias.DataBind();

            pnlResults.Visible = true;
        }

        protected void GridCategorias_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Cells[2].Attributes.Add("title", "Editar");
                    e.Row.Cells[3].Attributes.Add("title", "Eliminar");
                    ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    SetJavascriptForDeleteRecord(btnEliminarCtrl, ((MaestroBase)e.Row.DataItem).Nombre);                    
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridCategorias_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int categoriaId = Convert.ToInt32(this.GridCategorias.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCategoriaEdit + "?Id={0}", categoriaId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    int categoriaId = Convert.ToInt32(this.GridCategorias.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.EliminarCategoria(categoriaId);
                    Buscar();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridCategorias_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.GridCategorias.PageIndex = e.NewPageIndex;

                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void btnAgregarNuevo_Click(object sender, EventArgs e)
        {
            AgregarNuevaCategoria();
        }

        private void AgregarNuevaCategoria()
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCategoriaEdit, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.GridCategorias.AllowPaging;
                this.GridCategorias.AllowPaging = false;

                Buscar();                                

                GridViewExportExcelUtil.Export("Categorias.xls", this.GridCategorias, 0,1,2,3,4);
             
                this.GridCategorias.AllowPaging = previousAllowPaging;                
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}